import Vue from 'vue'
import VueRouter from 'vue-router'

import Login from "@/views/Login";

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect:'/login'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "about" */ '../views/Login.vue')
  },
  {
    path: '/home',
    component:()=> import('../views/Home'),
    redirect: "/welcome",
    children:[
      {
        path:'/welcome',
        component:()=> import('../views/Welcome'),
      },
      {
        path:'/user',
        component:()=> import('../views/admin/UserList'),
      },
      {
        path:'/books',
        component:()=> import('../views/BookList'),
      },
      {
        path:'/search',
        component:()=> import('../views/Search'),
      }
    ]
  }

]

const router = new VueRouter({
  routes
})

// 挂载路由守卫
router.beforeEach((to, from, next) => {

  // to:将要访问的路径
  // from:从哪里访问的路径
  // next:之后要做的任务，是一个函数
  //    next()放行， next（'/URL'）强制跳转的路径。
  if (to.path == '/login') return next();// 访问路径为登录
  // 获取flag
  const userFlag = window.sessionStorage.getItem("user");// session取值
  if (!userFlag) return next('/login');// 没登录去登录
  next();
})

export default router
